<?php

namespace app\report\logic;

use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;
use app\order\logic\OrderLogic;

class MonthlyDistributionLogic
{

    public function __construct()
    {
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function PersonalInfo($params = [])
    {
        $limit = $params['limit'] ?? 10;

        $id = $params['id'];
        $report_monthly_personal = Db::name('report_monthly_personal')->where('id',$id)->find();
        if(empty($report_monthly_personal)){
            return json(DefaultResponse(200, true, '暂无数据'));
        }
        $date = $report_monthly_personal['date'];
        $source = $report_monthly_personal['source'];
        
        $admin_id = $report_monthly_personal['admin_id'];

        $start_time = strtotime($date);
        $end_time = strtotime("+1 month", strtotime($date . "-01"));  
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        if($admin_id !== 85){
            $where[]  = ['fulfillment_status', 'in', ["fulfilled", "restocked","partial"]];
        }

        $status = $params['status'] ?? "";
        if(!empty($status)){
            switch ($status) {
                case 'fb':
                    $where[]  = ['source', 'in', ["fb", "tt"]];
                    $where[]  = ['admin_id', '=', $admin_id];
                    break;
                case 'email':
                    $where[]  = ['source', 'in', ["email", "ggad", "impact"]];
                    $where[]  = ['admin_id', '=', $admin_id];
                    break;
                case 'WithinTheChannel':
                    $where[]  = ['source', '=', $source];
                    $where[]  = ['admin_id', '<=', 0];
                    $where[]  = ['shop_id', 'in', [17, 5]];
                    break;
                case 'DirectCurrent':
                    $where[]  = ['source', 'in', ["other", "直接访问"]];
                    $where[]  = ['shop_id', 'in', [17, 5]];
                    break;
                case 'SheCurve':
                    $where[]  = ['admin_id', '=', $admin_id];
                    $where[]  = ['shop_id', '=', 17];
                    break;
                case 'SmallShop':
                    $where[]  = ['admin_id', '=', $admin_id];
                    $where[]  = ['shop_id', 'not in', [17, 5]];//大店
                    //TODO 特殊规则 7月业绩不算WomenForSure ,LilyLove用大店模式显示
                    if($date == '2024-07'){
                        $where[]  = ['shop_id', 'not in', [17, 5,10,18]];
                    }
                    break;
                default:
            }
        }else{
            $where[]  = ['admin_id', '=', $admin_id];
        }

        $list = Db::name('order_achievement')
            ->field('
                shop_id,
                name,
                createtime,
                financial_status,
                fulfillment_status,
                createtime,
                freight,
                skuquantity,
                estimate_freight,
                material,
                dispute,
                total_price,
                refund,
                tags,
                sku,
                freight_status,
                material_status,
                disputeapi_type,
                disputeapi_status,
                currency,
                source
            ')
            ->where($where)
            ->order("shop_id desc,createtime desc")
            ->paginate($limit);

        $lists = $list->items();

        $shops = Db::name('shops')
            ->field("id,name")
            // ->where('status',1)
            ->column('name', 'id');
        // halt($shops);
        //汇率
        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();

        $source = "";
        foreach ($lists as &$v) {
            $v['shop_name'] = $shops[$v['shop_id']];
            //判断金额
            $v = $this->handling_performance($v,$order_exchange);
            //计算利润
            if(empty($source) && !empty($v['source'])){
                $source = $v['source'];
            }
        }
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    public function handling_performance($v,$order_exchange)
    {
        $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
        //填充预估物流费
        if($v['freight'] <= 0.001){
            $v['freight'] = $v['estimate_freight'];
        }
        if(empty($v['fulfillment_status'])){
            $v['fulfillment_status'] = "未发货";
            $v['skuquantity'] = 0;
        }
        //物流--人民币转美金
        $v['freight'] = (float)number_format((float)$v['freight'] / $order_exchange['dollar'], 3, '.', '');
        //采购
        $v['material'] = (float)number_format((float)$v['material'] / $order_exchange['dollar'], 3, '.', '');
        // $v['LogisticsMarkupFee'] = (float)number_format((float)$v['skuquantity'] * $order_exchange['LogisticsMarkupFee'], 3, '.', '');
        $v['LogisticsMarkupFee'] = $order_exchange['LogisticsMarkupFee'];
        $v['dollar'] = $order_exchange['dollar'];

        $v['total_pricex'] = $v['total_price'];
        $v['freightx'] = $v['freight'];
        $v['materialx'] = $v['material'];
        $v['remarks'] = '';
        if(!empty($v['dispute_status']) && $v['dispute_status'] !== "争议赢"){
            $v['total_pricex'] = 0;
        }
        if($v['financial_status'] == 'paid' && $v['fulfillment_status'] !== 'fulfilled'){
            $v['total_pricex'] = 0;
            $v['freightx'] = 0;
            $v['materialx'] = 0;
            $v['remarks'] = $v['remarks'].'|已付款(未发货)不算业绩';
        }
        if($v['financial_status'] == 'refunded' && $v['fulfillment_status'] !== 'fulfilled'){
            $v['total_pricex'] = 0;
            $v['freightx'] = 0;
            $v['materialx'] = 0;
            $v['remarks'] = $v['remarks'].'|已退款(未发货)不算业绩';
        }
        if($v['financial_status'] == 'refunded' && $v['fulfillment_status'] == 'fulfilled'){
            $v['total_pricex'] = 0;
            $v['freightx'] = $v['freight'];
            $v['materialx'] = $v['material'];
            $v['remarks'] = $v['remarks'].'|已退款(已发货)不算销售额,计算成本';
        }
        return $v;
    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['日期', 'createtime'];
        $header[] = ['订单号', 'name'];
        $header[] = ['支付状态', 'financial_status'];
        $header[] = ['物流状态', 'fulfillment_status'];
        $header[] = ['现销售额$', 'total_price'];
        $header[] = ['件数', 'skuquantity'];
        $header[] = ['退款', 'refund'];
        $header[] = ['物流成本$', 'freight'];
        $header[] = ['采购成本$', 'material'];
        $header[] = ['争议成本$', 'dispute'];
        $header[] = ['美金汇率', 'dollar'];
        $header[] = ['币种', 'currency'];
        $header[] = ['原记录标签', 'tags'];
        $header[] = ['物流匹配状态', 'freight_status'];
        $header[] = ['采购匹配状态', 'material_status'];
        $header[] = ['争议类型', 'disputeapi_type'];
        $header[] = ['争议状态', 'disputeapi_status'];
        $header[] = ['SKU', 'sku'];

        //id参数
        $id = $params['id'] ?? 1;
        $report_monthly_personal = Db::name('report_monthly_personal')->where('id',$id)->find();
        if(empty($report_monthly_personal)){
            return json(DefaultResponse(200, true, '暂无数据'));
        }
        $date = $report_monthly_personal['date'];
        
        //汇率
        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();

        $admin_id = $report_monthly_personal['admin_id'];

        $timedate = strtotime($date);
        $start_time = $timedate;
        $end_time = strtotime("+1 month", strtotime($date . "-01"));  
        //相关运营归属记录
        $query_date = [
            'start_time'  => $start_time,
            'end_time' => $end_time,
            'admin_id' => $admin_id,
        ];
        $OrderLogic = new OrderLogic();
        $lists = $OrderLogic->OperationOwnership($query_date);
        if(empty($lists)){
            return json(DefaultResponse(200, true, '列表暂无数据'));
        }
        $Achievements = [];
        $count = 0;
        foreach ($lists as $k=>$v) {
            $shop_info = Db::name('shops')->where('id',$v['shop_id'])->find();
            //重新整理时间段
            $v = $OrderLogic->ReorganizeTimePeriods($v,$query_date);
            switch ($v['type']) {
                //单人店铺业绩
                case '1': 
                    $Achievement = $this->SinglePersonStorePerformance($v);
                    break;
                //多人店铺业绩
                case '2':
                    $Achievement = $this->MultiPersonStorePerformance($v);
                    break;
                default:
            }
            if(!empty($Achievement)){
                foreach ($Achievement as &$v) { 
                    $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
                    $v['shop_name'] = $shop_info['name'];
                    //填充预估物流费
                    if($v['freight'] <= 0.001){
                        $v['freight'] = $v['estimate_freight'];
                    }
                    if(empty($v['fulfillment_status'])){
                        $v['fulfillment_status'] = "未发货";
                    }
                    //物流--人民币转美金
                    $v['freight'] = (float)number_format((float)$v['freight'] / $order_exchange['dollar'], 3, '.', '');
                    //采购
                    $v['material'] = (float)number_format((float)$v['material'] / $order_exchange['dollar'], 3, '.', '');
                    $v['dollar'] = $order_exchange['dollar'];
                    $Achievements[] = $v;
                    $count++;
                    if($count >= 5000){
                        return '数据超过5000条,异步下载中，请2分钟后前往【任务组管理/系统导出管理】页面下载';
                    }
                }
            }
        }

        $fileName = $report_monthly_personal['date']."".$report_monthly_personal['admin_name']."业绩";
        return Excel::exportData($Achievements, $header, $fileName, 'xlsx');
    }

}
